<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 警告条 -->
    <el-card>
      <el-alert title="警告提示的文案" type="warning" show-icon :closable="false"></el-alert>
      <div style="margin:20px 0">
        商品分类:
        <!-- 级联写上 -->
        <el-cascader
          v-model="cascaderValue"
          :options=" GoodsCateList"
          :props="cascaderProps"
          @change="handleChange"
        ></el-cascader>
      </div>
      <!-- 标签页 -->
      <!--  v-model设置默认选择的值 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            @click="addParamsDialogVisible=true"
            :disabled="isBtnDisabled"
            size="mini"
          >添加参数1</el-button>
          <!-- 动态生成表格 -->
          <el-table :data="manyParams" border stripe>
            
            <el-table-column type="expand">
              <!-- 展开行  v-for  一定要搭载 ：key=""-->
              <template slot-scope="scope">
                <el-tag
                  @close="removeAttrVals(i,scope.row)"
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                >{{item}}</el-tag>
                <!-- 动态渲染文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>

            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog (scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="success"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addParamsDialogVisible=true"
          >添加参数2</el-button>
          <el-table :data="onlyParams" border stripe>


            <!-- 展开行 -->
           <el-table-column type="expand">
              <!-- 展开行  v-for  一定要搭载 ：key=""-->
              <template slot-scope="scope">
                <el-tag
                  @close="removeAttrVals(i,scope.row)"
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                >{{item}}</el-tag>
                <!-- 动态渲染文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>


            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog( scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!--    -->
    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      @close="closeAddParams"
      :visible.sync="addParamsDialogVisible"
      width="40%"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsRules"
        ref="addParamsRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      @close="closeEditParams"
      :visible.sync="editParamsDialogVisible"
      width="40%"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsRules"
        ref="editParamsRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 商品分类数据
      // label    GoodsCateList     :options=" GoodsCateList"这三个出错没有出现数据
      GoodsCateList: [],

      cascaderValue: [],
      cascaderProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id"
      },
      onlyParams: [],
      manyParams: [],
      addParamsDialogVisible: false,
      addParamsForm: {
        attr_name: ""
      },

      addParamsRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" }
        ]
      },
      editParamsForm: {
        attr_name: ""
      },

      editParamsRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" }
        ]
      },
      editParamsDialogVisible: false,

      //默认选择first的
      activeName: "many"
    };
  },
  created() {
    this.getGoodsCateList();
    this.handleChange();
  },
  methods: {
    async getGoodsCateList() {
      const { data: res } = await this.$http.get("categories");
      //    console.log(res);

      if (res.meta.status !== 200) return this.$message.error("获取数据失败");
      this.GoodsCateList = res.data;
      console.log(this.GoodsCateList);
    },
    //封装一个参数
    async getParams() {
      if (this.cascaderValue.length !== 3) return (
        this.cascaderValue = [],
        // 选择3级数据以外的数据 清空 页面
           this.onlyParams=[],
          this.manyParams=[]
        );
      console.log(this.cascaderValue);
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      );
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("数据获取失败");

      //将vals转换成数组
      res.data.forEach(item => {
        //  item.attr_vals=item.attr_vals.split(' ')
        // 如果是空字符串 返回[],不是空字符串 利用split分割
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        //控制文本框的显示或隐藏
        item.inputVisible = false;
        item.inputValue = "";
      });

      //   看结果是什么来分清静态和动态的函数
      if (this.activeName === "only") {
        this.onlyParams = res.data;
      } else {
        this.manyParams = res.data;
      }
    },

    // 只能3级能点 点击选择的时候 才会触发
    async handleChange() {
      this.getParams();
    },
    handleTabsClick() {
      this.getParams();
    },
    // 添加关闭对话框
    closeAddParams() {
      this.$refs.editParamsRef.resetFields();
    },
    addParams() {
      this.$refs.addParamsRef.validate(async flag => {
        if (!flag) return this.$message.error("未填写表单");
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          }
        );
        console.log(res);

        if (res.meta.status !== 201) return this.$message.error("创建失败");
        this.addParamsDialogVisible = false;
        // 重新运行数据
        this.getParams();
        // this.cascaderValue=res.data
      });
    },
    closeEditParams() {
      this.$refs.editParamsRef.resetFields();
    },
    editParams() {
      this.$refs.editParamsRef.validate(async flag => {
        if (!flag) return this.$message.error("未填写表单");
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName,
            attr_vals:this.editParamsForm.attr_vals
          }
        );

        if (res.meta.status !== 200) return this.$message.error("更新失败");
        this.$message.success("更新成功");
        this.editParamsDialogVisible = false;
        this.getParams();
      });
    },
    //   修改的迟点自己做 attributes/${attr_id}这是/

    async showEditDialog(attr_id) {
      this.editParamsDialogVisible = true;
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`
      );
      console.log(res);

      //    console.log(attr_id,this.cateId);
      this.editParamsForm = res.data;
    },

    // 删除参数
    removeParams(attr_id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          console.log("确认删除", attr_id);
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${attr_id}`
          );
          console.log(res);
          if (res.meta.status !== 200) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.getParams();
        })
        .catch(() => {
          this.$message("已取消删除");
        });
    },
    //  封装一个函数 上传数据用
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("更新失败");
      this.$message.success("更新成功");
    },


   // 上传数据到页面
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      //输入框的值合法
      // console.log("运行成功");
      // var flag=false
      //   row.attr_vals.forEach(item=>{
      //       if(item===row.inputValue.trim() ){
      //         flag=true
      //       }

      //   })
                 
  
      // if(flag) return this.$message.error('这属性已经存在')
         const index=row.attr_vals.findIndex(item=>item===row.inputValue.trim())
         if(index!==-1) return this.$message.error('属性已经存在')
         row.attr_vals.push(row.inputValue)
         row.inputValue=''
         row.inputVisible=false
         this.saveAttrVals(row)
           
         



      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      // 做完后上传到客服端
      this.saveAttrVals(row);
    },
    // 删除数据从页面
    removeAttrVals(index, row) {
      row.attr_vals.splice(index, 1);
      // 做完后上传到客服端
      this.saveAttrVals(row);
    },

    showInput(row) {
      row.inputVisible = true;
      // 页面渲染后才用  数据修改完成后 不代表页面修改完成
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    }
  },
  computed: {
    isBtnDisabled() {
      //   if(this.cascaderValue.length !==3){ return true}
      //   return false
      return this.cascaderValue.length !== 3;
    },
    // 分累后的id
    cateId() {
      return this.cascaderValue.length !== 3 ? null : this.cascaderValue[2];
    },
    titleText() {
      return this.activeName === "many" ? "动态属性" : "静态属性";
    }
  }
};
</script>
<style scoped lang="less">
.el-tag {
  margin: 7px;
}
.input-new-tag {
  width: 120px;
}
</style>